package com.kehutong.admin.controler.app;

import java.util.List;

import org.coraframework.authz.HasPermission;
import org.coraframework.authz.SubjectUtil;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONObject;
import org.coraframework.mvc.MvcAction;
import org.coraframework.mvc.http.Bean;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.util.Objects;

import com.kehutong.admin.entity.app.AppMenu;
import com.kehutong.common.entity.TreeUtil;

@MvcAction
@ReqMapping("/admin/app/menu")
public class AppMenuController {
	
	private static final String APP_MENU = "app_menu";

    @Inject
    private JdbcSession jdbcSession;

    @ReqMapping("/list")
    public Object list(JSONObject jsonObject) throws Exception {
    	return jdbcSession.findArray(AppMenu.class)
	    			.eq(jsonObject, "pid", "show")
	    			.eq("deleted", false)
    				.exe();
    }
    
    @ReqMapping(value = "/tree")
    public Object listAsTree(JSONObject jsonObject) throws Exception {
    	AppMenu root = SubjectUtil.getSubject().getAttr(APP_MENU);
    	if (Objects.isNull(root)) {
    		List<AppMenu> menuList = jdbcSession.findArray(AppMenu.class)
				.eq(jsonObject, "pid", "show")
				.eq("deleted", false)
				.order("sort", "desc")
				.exe();
    		root = TreeUtil.organizeAsTree(menuList, false);
    	}
       
        return Result.success(root);
    }

    @HasPermission("app:menu:view")
    @ReqMapping("/get")
    public Object getById(AppMenu item) {
    	return item;
    }

    @Bean(newInstance=true, copy=true)
    @HasPermission("app:menu:edit")
    @ReqMapping("/save")
    public Object save(AppMenu item) {
    	jdbcSession.insert(item);
		
        return Result.success();
    }
    
    @Bean(copy=true)
    @HasPermission("app:menu:edit")
    @ReqMapping("/update")
    public Object update(AppMenu item) throws Exception {
		jdbcSession.updateById(item);
        return Result.success();
    }
    
    @HasPermission("app:menu:edit")
    @ReqMapping("/delete")
    public Object deleteById(AppMenu item) {
		item.setDeleted(true);
		jdbcSession.updateById(item);
    	
        return Result.success();
    }

    @HasPermission("app:menu:edit")
    @ReqMapping("/sort")
    public Object sort(AppMenu menu) {
    	
    	jdbcSession.updateById(menu);
        return Result.success();
    }
}
